//
//  LeftSideVC
//  ShareUmbrella
//
//  Created by niupark on 2017/8/5.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import YSKit
import RxSwift
import SDWebImage


class  BoardItem {
    var title = ""
    var image: UIImage?
    var action: (()->Void)?
    init(title: String, image: UIImage? = UIImage(named: ""), action:(()->Void)? = nil) {
        self.title = title
        self.image = image
        self.action = action
    }
    class func empty() -> BoardItem {
        return BoardItem(title: "", image: nil, action: nil)
    }
}


class LeftSideVC: YSBaseViewController {

    fileprivate var collectionView: UICollectionView?
    fileprivate let headerImageView = UIImageView()
    fileprivate var nameLabel: UILabel!
    fileprivate var editImageView: UIImageView?

    var actionList: [BoardItem]!
    override func setup() {
        super.setup()
        self.actionList  = [BoardItem(title: I18n("VC.LFSide.account.titlte"), image: UIImage(named:"我的账户icon"), action: {[weak self]() in
            guard let `self` = self else {
                return
            }
            self.revealViewController()!.revealToggle(nil)
            self.fontVC?.ys.push(MyAccountVC())

        }), BoardItem(title: I18n("VC.LFSide.help.titlte"), image: UIImage(named:"我的帮助icon"), action: { [weak self]() in
            guard let `self` = self else {
                return
            }
            self.revealViewController()!.revealToggle(nil)
            self.fontVC?.ys.push(MyHelpVC())

            
        }), BoardItem(title: I18n("VC.LFSide.piontshop.titlte"), image: UIImage(named:"积分商城icon"), action: { [weak self]() in
            guard let `self` = self else {
                return
            }
            self.revealViewController()!.revealToggle(nil)
            //self.fontVC?.ys.push(PointShopVC())
            self.fontVC?.ys.push(IntegralShopVC())

            
        }), BoardItem(title: I18n("VC.LFSide.fadeback.titlte"), image: UIImage(named:"用户反馈icon"), action: { [weak self]() in
            guard let `self` = self else {
                return
            }
            self.revealViewController()!.revealToggle(nil)
            self.fontVC?.ys.push(FadebackVC())

            
        }), BoardItem(title: I18n("VC.LFSide.setting.titlte"), image: UIImage(named:"设置icon"), action: { [weak self]() in
            guard let `self` = self else {
                return
            }
            self.revealViewController()!.revealToggle(nil)
            self.fontVC?.ys.push(SettingVC())

            
        }), BoardItem(title: I18n("VC.LFSide.exit.titlte"), image: UIImage(named:"退出icon"), action: {
            let optionMenu = UIAlertController(title: nil, message:"退出后不会删除任何历史数据", preferredStyle:.actionSheet)
            let exitAction = UIAlertAction(title: "确定", style: .default, handler:{ (alert: UIAlertAction!) -> Void in
                self.revealViewController()!.revealToggle(nil)
                Auth.logout()
            })
            
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: { (alert: UIAlertAction!) -> Void in
                
            })
            
            optionMenu.addAction(exitAction)
            optionMenu.addAction(cancelAction)
            
            self.present(optionMenu, animated: true, completion: nil)
        })]
    }
    //界面布局
    override func buildUI() {
        super.buildUI()
        self.title = I18n("VC.home.title")
        
        let bgLeftVC = UIImageView(image: UIImage(named: "侧边栏背景"))
        bgLeftVC.contentMode = .scaleToFill
        self.view.addSubview(bgLeftVC)

        self.collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.newLayout()).ys.customize({ (view) in
            self.view.addSubview(view)
            view.isScrollEnabled = false
            view.delegate = self
            view.dataSource = self
            view.register(MineActionitemCVC.self, forCellWithReuseIdentifier: MineActionitemCVC.className())
            
            view.backgroundColor = .clear
            view.snp.makeConstraints({ (make) in
                make.leading.equalTo(self.view).offset(45)
                make.bottom.equalTo(self.view).offset(-80)
                make.width.equalTo(220)
                make.height.equalTo(330)

            })
        })
        
        let vWhiteBg = UIView(frame: .zero).ys.customize({ (view) in
            self.view.addSubview(view)
            view.backgroundColor = UIColor.white
            view.layer.cornerRadius = 86.0/2.0
            view.layer.masksToBounds = true
            
            view.snp.makeConstraints({ (make) in
                make.centerX.equalTo(self.collectionView!)
                make.top.equalTo(40)
                make.width.height.equalTo(86);
            })
            
        })
        
        self.headerImageView.layer.cornerRadius = 80.0/2.0
        self.headerImageView.layer.masksToBounds = true

        _  = UserService.sharedInstance.headLogo.asObservable().takeUntil(self.rx.deallocated).subscribe(onNext: { [weak self] (headlogo) in
            guard let `self` = self else {
                return
            }
            guard let url = headlogo else {
                self.headerImageView.image = UIImage(named: "空白头像")

                return
            }

            self.headerImageView.sd_setImage(with: URL(string: url), placeholderImage:  UIImage(named: "空白头像"), options: SDWebImageOptions.highPriority, completed: nil)

        })
        
        self.view.addSubview(self.headerImageView)
        
        self.headerImageView.snp.makeConstraints({ (make) in
            make.centerX.centerY.equalTo(vWhiteBg)
            make.width.height.equalTo(80);
        })
        
        self.nameLabel = UILabel(frame: .zero)
        self.nameLabel.text = UserService.sharedInstance.name.value
        self.nameLabel.textColor = UIColor.white
        self.view.addSubview(self.nameLabel!)
        self.nameLabel.snp.makeConstraints({ (make) in
            make.top.equalTo(vWhiteBg.snp.bottom).offset(10)
            make.centerX.equalTo(vWhiteBg).offset(-10)
        })
        
        
        self.editImageView = UIImageView(frame: CGRect.zero);
        self.editImageView!.image = UIImage(named: "空白头像")
        self.view.addSubview(self.editImageView!)
        
        self.editImageView!.snp.makeConstraints({ (make) in
            make.leading.equalTo(self.nameLabel.snp.trailing).offset(5)
            make.centerY.equalTo((self.nameLabel.snp.centerY))
            make.width.height.equalTo(20);
        })
        
        let btnCenter =   UIButton(type: UIButtonType.system).ys.customize { (view) in
            self.view.addSubview(view)
            view.snp.makeConstraints({ (make) in
                make.top.equalTo(vWhiteBg.snp.top)
                make.leading.equalTo(self.view.snp.leading).offset(30)
                make.width.equalTo(250)
                make.bottom.equalTo((self.editImageView!.snp.bottom))
            })
        }
        
        _ = btnCenter.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                
                self?.revealViewController()!.revealToggle(nil)
                let vc = MineCenterVC(config: UserConfiges())
                
                self?.fontVC?.ys.push(vc)
                
            })

        getUserInfo()
        
    }
    
    func getUserInfo() -> Void {
        _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.userInfo(token: Auth.token))).subscribe(onNext: { [weak self] (data) in
            //
            HUD.hide()
            guard let _ = self else {
                return
            }
            
            guard let userInfo = data else{
                return
            }
            
            UserService.sharedInstance.km.value = userInfo["data"]["sharedistance"].string ?? "0"
            UserService.sharedInstance.times.value = userInfo["data"]["sharemins"].string ?? "0"
            UserService.sharedInstance.point.value = userInfo["data"]["score"].string ?? "0"
            UserService.sharedInstance.count.value = userInfo["data"]["sharetimes"].string ?? "0"
            
            }, onError: { [weak self](ErrorType) in
                HUD.hide()
                guard let  `self` = self else {
                    return
                }
                self.handle(withError: ErrorType)
        })

    }
    
    func newLayout() ->  UICollectionViewFlowLayout{
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 110, height: 110)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .vertical
        layout.sectionInset =  UIEdgeInsetsMake(0, 0, 20, 0)
        
        return layout
    }
    //
    
    override func buildRx() {
        super.buildRx()
        
    }
    
}


extension LeftSideVC: UICollectionViewDelegate, UICollectionViewDataSource {
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return  self.actionList.count
    }
    
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MineActionitemCVC.className(), for: indexPath) as! MineActionitemCVC
        
        cell.lineColor = YSColor.c104.color
        
        let actionItem = self.actionList[indexPath.row]
        
        //划线
        switch indexPath.row {
        case 0,2:
            cell.linwSeparatorOptions = [.right, .bottom]
        case 1,3:
            cell.linwSeparatorOptions = [.bottom]
        case 4:
            cell.linwSeparatorOptions = [.right]
        default:
            cell.linwSeparatorOptions = []

        }
        cell.updateUI(actionItem.image, title: actionItem.title)
        
        return cell
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        let actionItem = self.actionList[indexPath.row]
        guard let action  = actionItem.action else {
            return
        }
        action()
    }
    
    
    public func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
        return false
    }
}


extension LeftSideVC {
    var fontVC: UIViewController? {
       return APP.currentVC
    }
}
